package com.yuanfeng.business.service.impl;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.business.dto.*;
import com.yuanfeng.business.entity.ShopBaseEntity;
import com.yuanfeng.business.entity.ShopRecordEntity;
import com.yuanfeng.business.entity.ShopRegistrationEntity;
import com.yuanfeng.business.mapper.ShopBaseMapper;
import com.yuanfeng.business.mapper.ShopRecordMapper;
import com.yuanfeng.business.mapper.ShopRegistrationMapper;
import com.yuanfeng.business.service.ShopRegistrationService;
import com.yuanfeng.business.vo.QuUsablePrecinctVO;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.dto.goods.ActivityNoneUpdateDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.util.secverifyapiutil.Base64Utils;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class ShopRegistrationServiceImpl extends ServiceImpl<ShopRegistrationMapper, ShopRegistrationEntity>
    implements ShopRegistrationService{
    @Resource
    private ShopRecordMapper shopRecordMapper;
    @Resource
    private ShopBaseMapper shopBaseMapper;
    @Override
    public ResponseResult insertShopRegistration(ShopRegistrationDTO param) {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = dateformat.format(new Date());
        param.setOperationTime(startTime);
        String desc = param.getActivityDesc();
        if (desc.length() > 1000) {
            return ResponseResult.fail(BizCodeEnume.REGISTRATION_DESCRIPTION_TOO_LONG);
        }
        String fromBase64 = null;
        try {
            String data = param.getActivityDesc();
            fromBase64 = Base64Utils.getFromBase64(data);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(BizCodeEnume.DECODING_FAILED);
        }
        param.setActivityDesc(fromBase64);
        this.baseMapper.insertShopRegistration(param);

        return ResponseResult.success();

    }

    @Override
    public ResponseResult updateShopRegistration(ShopRegistrationDTO param) {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String desc = param.getActivityDesc();
        if (desc.length() > 1000) {
            return ResponseResult.fail(BizCodeEnume.REGISTRATION_DESCRIPTION_TOO_LONG);
        }
        String data = param.getActivityDesc();
        if(Base64.isBase64(data)){
            try {
                String fromBase64 = Base64Utils.getFromBase64(data);
                param.setActivityDesc(fromBase64);
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseResult.fail(BizCodeEnume.DECODING_FAILED);
            }
        }
        String startTime = dateformat.format(new Date());
        param.setOperationTime(startTime);
        Integer integer = this.baseMapper.updateShopRegistration(param);
        return ResponseResult.success(integer);
    }

    @Override
    public ResponseResult queryShopRegistration(ShopRegistrationDTO param) {
        ShopRegistrationEntity entity=this.baseMapper.selectById(param.getActivityId());
        return ResponseResult.success(entity);
    }

    @Override
    public ResponseResult deleteShopRegistration(ShopRegistrationDTO param) {
        this.baseMapper.delete(new LambdaQueryWrapper<ShopRegistrationEntity>()
                       .eq(ShopRegistrationEntity::getActivityId,param.getActivityId()));
        return ResponseResult.success();
    }

    @Override
    public ResponseResult selectShopRegistration(ShopRegistrationDTO param) throws IllegalAccessException {
        Map data= ParseMapUtils.beanToMap(param);
        IPage<ShopRegistrationDTO> page=this.baseMapper.selectShopRegistration(new Query<ShopRegistrationDTO>().getPage(data),
                param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryActiveName(UserTokenBeanDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());
        Map<String,Object> map=new HashMap<>();
        if (userPermissionsResult.getFlag()) {
            List<QuUsablePrecinctVO> quUsablePrecincts = this.baseMapper.queryActiveName();
            map.put("result",quUsablePrecincts);
            map.put("count",quUsablePrecincts.size());

        }
        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult addActivityGoods(ManageActivityGoodsAddDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (userPermissionsResult.getFlag()) {
            //通过专区活动id查询当前店铺是否已经参见当前专区报名 如果没有参加就参加
            Integer cout = shopRecordMapper.selectCount(new LambdaQueryWrapper<ShopRecordEntity>()
                            .eq(ShopRecordEntity::getShopId,userPermissionsResult.getShopId())
                            .eq(ShopRecordEntity::getActivityId,param.getActivityId()));
            if(0 == cout){
                ShopRecordEntity shopRecordPojo = new ShopRecordEntity();
                ShopRegistrationEntity shopRegistration = this.baseMapper.selectOne(new LambdaQueryWrapper<ShopRegistrationEntity>()
                        .eq(ShopRegistrationEntity::getActivityId,param.getActivityId())
                        .orderByDesc(ShopRegistrationEntity::getActivityId));
                shopRecordPojo.setParticipationTime(new Date());
                shopRecordPojo.setActivityId(shopRegistration.getActivityId());
                shopRecordPojo.setActivityType(shopRegistration.getAreaType());
                ShopBaseEntity shopBaseEntity = shopBaseMapper.selectById(userPermissionsResult.getShopId());
                shopRecordPojo.setShopAddress(shopBaseEntity.getShopAddress());
                shopRecordPojo.setShopDetail(shopBaseEntity.getShopDetail());
                shopRecordPojo.setShopGradeId(shopBaseEntity.getShopGradeId());
                shopRecordPojo.setShopId(shopBaseEntity.getShopId());
                shopRecordPojo.setShopName(shopBaseEntity.getShopName());
                shopRecordPojo.setUserId(shopBaseEntity.getUserId());
                shopRecordMapper.insert(shopRecordPojo);
            }
            param.setUpdateBy(String.valueOf(userPermissionsResult.getUserId()));

            Integer noneType = param.getOpType();
            param.setUpdateDate(new Date());
            param.setActivityVerify(10);
            List<Integer> commonIdList = param.getCommonIdList();

            List<ActivityNoneUpdateDTO> noneGoodsList = Lists.newArrayList();
            for (Integer commonId : commonIdList) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("commonId", commonId);
                paramMap.put("noneType", noneType);

                param.setCommonId(commonId);
                Integer commonId2 = this.baseMapper.checkGoodsIsExist(paramMap);
                // 判断是否已存在
                if (null != commonId2 && commonId2 > 0) {

                    return ResponseResult.success(BizCodeEnume.PRODUCT_ALREADY_EXISTS);
                }

                ActivityNoneUpdateDTO noneGoods = new ActivityNoneUpdateDTO();
                noneGoods.setCommonId(commonId);
                noneGoods.setUpdateDate(new Date());
                noneGoods.setOpType(noneType);
                noneGoodsList.add(noneGoods);
            }

            if (!CollectionUtils.isEmpty(noneGoodsList)) {
                this.baseMapper.insertActivityGoods(noneGoodsList);

            }

        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

        return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
    }

    @Override
    public ResponseResult selectNewVersion() {
        List<MerchantVersionDTO> list = this.baseMapper.selectNewVersion();
        return ResponseResult.success(list);
    }

    @Override
    public ResponseResult selectNewShopRegist() {
        List<ShopRegistrationDTO> list = this.baseMapper.selectNewShopRegist();
        return ResponseResult.success(list);
    }

    @Override
    public ResponseResult insertShopRecord(ShopRecordDTO param) {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = dateformat.format(new Date());
        String token = param.getToken();
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (ui == null) {
            return ResponseResult.fail(10086, "没有权限");
        }
        List<ShopRegistrationDTO> list = this.baseMapper.selectNewShopRegist();
        param.setParticipationTime(startTime);
        param.setActivityId(list.get(0).getActivityId());
        param.setActivityType(list.get(0).getAreaType());
        List<ShopRecordDTO> list2 = this.baseMapper.selectShopXinXi(ui.getShopId());
        param.setShopAddress(list2.get(0).getShopAddress());
        param.setShopDetail(list2.get(0).getShopDetail());
        param.setShopGradeId(list2.get(0).getShopGradeId());
        param.setShopId(list2.get(0).getShopId());
        param.setShopName(list2.get(0).getShopName());
        param.setUserId(list2.get(0).getUserId());
        this.baseMapper.insertShopRecord(param);
        return ResponseResult.success();
    }
}




